#include "bridgeobjectmanager.h"

BridgeObjectManager::BridgeObjectManager(const QString& framework_name)
    : framework_name_(framework_name)
{
}

void BridgeObjectManager::registerObject(const QString& id, const BridgeObject& obj)
{
    objects_.insert(id, obj);
}

void BridgeObjectManager::unregisterObject(const QString& id)
{
    objects_.remove(id);
}

void BridgeObjectManager::invokeCallback(const QString& uniform_callback, const QString& args)
{
    QString object_id, callback;
    if (resolveUniformObjectId(uniform_callback, object_id, callback)) {
        BridgeObject obj = objects_.value(object_id);
        if (obj.callbackFilter().isValid()) {
            obj.callbackFilter()(callback, args);
        } else if (obj.callbacks().contains(callback)) {
            obj.callbacks().value(callback)(args);
        }
    }
}

QString BridgeObjectManager::uniformObjectId(const QString& object_id,
                                             const QString& object_callback)
{
    return QString("%1.%2").arg(object_id, object_callback);
}

bool BridgeObjectManager::resolveUniformObjectId(const QString& object_id, QString& object,
                                                 QString& id)
{
    int i = object_id.indexOf('.');
    if (i != -1) {
        object = object_id.left(i);
        id = object_id.mid(i + 1);
        return true;
    }
    return false;
}

QString BridgeObjectManager::bridgeObjectId()
{
    static int id = 1;
    QString object_id = QString("YCBuiltinBridgeObject%1").arg(id++);
    return object_id;
}
